const express = require('express')
const http = require('http')
const cors = require('cors')

const app = express()


const server = http.createServer(app)

app.use(cors())

const io = require('socket.io')(server, {
    cors: {
        origin: '*',
        methods: ['GET', 'POST']
    }
})


io.on('connection', (socket) => {
    console.log('新连接建立:', socket.id);

    // 响应连接成功
    socket.emit('connect_success', socket.id);

    // 信令连接断开
    socket.on('disconnect', () => {
        console.log('信令连接断开:', socket.id);
        socket.broadcast.emit('callEnded');
    });

    // 信令连接错误
    socket.on('connectionError', ({ to, message }) => {
        console.error(`信令连接错误: ${message}`);
        if (to) {
            io.to(to).emit('callError', { message });
        }
        socket.emit('callError', { message });
    });

    // 发起呼叫
    socket.on('sendCall', ({ userToCall, signal, from, name }) => {
        console.log(`用户 ${from} (${name}) 呼叫 ${userToCall}`);
        console.log('信号数据类型:', typeof signal);

        // 检查目标用户是否在线
        const targetSocket = io.sockets.sockets.get(userToCall);
        if (!targetSocket) {
            console.log(`目标用户 ${userToCall} 不在线`);
            // 可以选择通知呼叫方目标用户不在线
            socket.emit('callError', { message: '对方不在线或无法接通' });
            return;
        }

        // 传递给接收方
        io.to(userToCall).emit('receiveCall', { signal, from, name });
        console.log('呼叫信号已发送');
    });

    // 接听呼叫
    socket.on('answerCall', ({ signal, to, name }) => {
        console.log(`用户 ${socket.id} (${name}) 接听来自 ${to} 的呼叫`);
   
        // 检查呼叫方是否仍在线
        const callerSocket = io.sockets.sockets.get(to);
        if (!callerSocket) {
            console.log(`呼叫方 ${to} 已不在线`);
            socket.emit('callError', { message: '呼叫方已断开连接' });
            return;
        }

        // 接收通话
        io.to(to).emit('callAccepted', { signal, name });
        console.log('接听信号已发送');
    });

    // 断开连接
    socket.on('callEnded', ({ to }) => {
        console.log(`通话结束: ${socket.id} -> ${to}`);
        // 只有两个人,直接广播即可
        if (io.broadcast) {
            io.broadcast.emit('callEnded')
        }
    });


})



const PORT = process.env.PORT || 12345;
server.listen(PORT, () => console.log(`Server is running on port ${PORT}`));





